import echarts from "echarts";
import zrender from "zrender";
import { toRad } from "../utils";
import { animateRotate } from "./base";

const elements = {};

function draw(chart, percentage) {
   let radialGradient = new echarts.graphic.RadialGradient(0.5, 0.5, 0.5, [
    { offset: 0, color: "rgba(0, 0, 0, 0)" },
    { offset: 1, color: "rgba(0, 138, 175, 0.5)" }
  ]);

  let zr = chart.getZr();
  let cx = zr.getWidth() / 2;
  let cy = zr.getHeight() / 2;


  let outerCircle = new zrender.Circle({
    origin: [cx, cy],
    shape: {
      cx: cx,
      cy: cy,
      r: 65
    },
    style: {
      fillOpacity: 0,
      stroke: "#009adb",
      strokeOpacity: 0.8,
      lineWidth: 2,
      lineDash: [4],
    },
    z: 0
  });

  let innerCircle = new zrender.Circle({
    origin: [cx, cy],
    shape: {
      cx: cx,
      cy: cy,
      r: 40
    },
    style: {
      fill: radialGradient,
      fillOpacity: 1,
      // stroke: "#009adb",
      strokeOpacity: 0,
      // lineWidth: 2,
      // lineDash: [4],
      text: percentage + '%',
      fontSize: "20",
      textFill: "rgba(255, 255, 255, 0.8)"
    },
    z: 2
  });


  zr.add(outerCircle);
  zr.add(innerCircle);
  animateRotate(outerCircle);
  drawArcAndCircle(zr, cx, cy);

  elements.innerCircle = innerCircle;
}

/**
 * 中间形状（圆圈+圆弧）
 * @param {*} zr 
 * @param {*} cx 
 * @param {*} cy 
 */
function drawArcAndCircle(zr, cx, cy) {
  let arcOpts = [
    {
      startAngle: 0,
      endAngle: 60,
      reverse: false
    },
    {
      startAngle: 120,
      endAngle: 180,
      reverse: false
    },
    {
      startAngle: 240,
      endAngle: 300,
      reverse: false
    },
  ];

  let group = new zrender.Group({
    origin: [cx, cy],
  });

  arcOpts.forEach(arcOpt => {
    let arc = new zrender.Arc({
      origin: [cx, cy],
      shape: {
        cx: cx,
        cy: cy,
        r: 55,
        startAngle: toRad(arcOpt.startAngle),
        endAngle: toRad(arcOpt.endAngle)
      },
      style: {
        fill: null,
        stroke: '#009adb',
        lineWidth: 10
      }
    });
    group.add(arc);
  });

  let circle = new zrender.Circle({
    origin: [cx, cy],
    shape: {
      cx: cx,
      cy: cy,
      r: 50
    },
    style: {
      // fill: gradient,
      // fillOpacity: 0.5,
      fill: null,
      stroke: "#009adb",
      lineWidth: 2,
    },
    z: 1
  });

  group.add(circle);
  zr.add(group);
  animateRotate(group, false);

}



function update(percentage) {
  elements.innerCircle.attr({
    style: {
      text: percentage + '%',
    }
  });
}



export default {
  draw,
  update
}
